<template>
  <!--引用表格-->
  <BasicTable @register="registerTable" :rowSelection="rowSelection">
    <!--插槽:table标题-->
    <template #tableTitle>
      <!--<a-button  type="primary" preIcon="ant-design:plus-outlined"  v-auth="'user:add'" @click="handleCreate" > 新增</a-button> -->
      <a-button type="primary" preIcon="ant-design:export-outlined" @click="handlerGenCode">生成代码</a-button>
      <a-button type="primary" preIcon="ant-design:import-outlined" @click="handlerImportDbTable">导入数据库表</a-button>
      <a-button type="primary" preIcon="ant-design:import-outlined" @click="handlerImportDocumentTable">导入Word中表</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <template #overlay>
          <a-menu>
            <a-menu-item key="1" @click="batchHandleDelete">
              <Icon icon="i-ant-design:delete-outlined" />
              删除
            </a-menu-item>
          </a-menu>
        </template>
        <a-button
          >批量操作
          <Icon icon="i-mdi:chevron-down" />
        </a-button>
      </a-dropdown>
    </template>
    <template #action="{ record }">
      <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
    </template>
  </BasicTable>
  <!--导入数据表-->
  <ImportDbTable @register="importDbTableDrawer" @select="handleImportTable" />
  <!--导入Word文件中的数据表-->
  <ImportDocumentTableDrawer @register="importDocumentTableDrawer" @success="handlerSuccess" />
  <GenCodeModal @register="registerGenCodeModal" @success="handlerSuccess" />
  <DbTableModal @register="registerDbTableModal" />
</template>

<script lang="ts" name="gen-table" setup>
  import { onMounted, unref, h } from "vue"
  import { BasicTable, TableAction, ActionItem } from "/@/components/Table"
  import { useDrawer } from "/@/components/Drawer"
  import ImportDbTable from "/@/views/addon/onlineDev/datasource/ImportDbTable.vue"
  import { listAllDataSource } from "/@/views/addon/onlineDev/datasource/api"
  import ImportDocumentTableDrawer from "./components/ImportWordTableDrawer.vue"
  import DbTableModal from "./components/DbTableModal.vue"
  import GenCodeModal from "./components/GenCodeModal.vue"
  import { useListPage } from "/@/hooks/system/useListPage"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { list, deleteGenTable, batchDeleteGenTable, importDbTable, syncDbTable } from "./codeGen.api"

  import { useModal } from "/@/components/Modal"
  import { columns, searchFormSchema } from "./codeGen.data"
  import { Icon } from "/@/components/Icon"

  const { createMessage, createConfirm } = useMessage()

  const [importDbTableDrawer, { openDrawer: openImportDbTableDrawer }] = useDrawer()
  const [importDocumentTableDrawer, { openDrawer: openImportDocumentTableDrawer }] = useDrawer()
  const [registerDbTableModal, { openModal: openDbTableModal }] = useModal()
  const [registerGenCodeModal, { openModal: openGenCodeModal }] = useModal()

  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    designScope: "gen-table",
    tableProps: {
      title: "生成代码表",
      api: list,
      columns: columns,
      immediate: false,
      size: "small",
      formConfig: {
        schemas: searchFormSchema,
      },
      bordered: false,
      actionColumn: {
        width: 150,
        title: "操作",
        dataIndex: "action",
        fixed: "right",
        slots: { customRender: "action" },
      },
      beforeFetch: (params) => {
        return Object.assign({ column: "createTime", order: "desc" }, params)
      },
    },
  })

  const [registerTable, { reload, clearSelectedRowKeys, getForm }, { rowSelection, selectedRowKeys }] = tableContext

  onMounted(async () => {
    const resp = await listAllDataSource()
    const options = unref(resp)
    if (options && options.length > 0) {
      const fromInstance = await getForm()
      fromInstance.updateSchema({
        field: "datasourceId",
        componentProps: {
          optionFilterProp: "label",
          showSearch: true,
          options,
        },
      })
      fromInstance.setFieldsValue({ datasourceId: options[0].id })
      reload()
    }
  })

  /**
   * 数据库表
   */
  function handlerImportDbTable() {
    openImportDbTableDrawer(true, {})
  }

  /**
   * 导入word中的表
   */
  function handlerImportDocumentTable() {
    createConfirm({
      iconType: "info",
      title: "Word文档格式要求",
      content: () =>
        h("div", {}, ["1. 除了数据库表格之外不能有多余的表格", h("br"), "2. 标题格式: 表说明 + 空格 + 表名(只能是英文+下划线, 其他符号被会去掉"]),
      onOk: () => {
        openImportDocumentTableDrawer(true, {})
      },
    })
  }

  /**
   * 编辑
   */
  async function handleEdit(record: Recordable) {
    openDbTableModal(true, { record })
  }

  const handlerGenCode = async () => {
    const keys = selectedRowKeys.value
    console.log("selectedRowKeys: ", keys)
    if (keys.length > 1) {
      createMessage.warning("生成代码只能选择一条数据")
      return
    }
    if (!keys[0]) {
      createMessage.warn("请选择表")
      return
    }

    openGenCodeModal(true, { id: keys[0] })
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteGenTable({ id: record.id })
    reload()
  }

  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: "同步",
        onClick: handleSyncDbTable.bind(null, record),
      },
      {
        label: "编辑",
        onClick: handleEdit.bind(null, record),
      },
      {
        label: "删除",
        color: "error",
        popConfirm: {
          title: "是否确认删除",
          confirm: handleDelete.bind(null, record),
        },
      },
    ]
  }

  const batchHandleDelete = async () => {
    console.log("selectKeys: ", selectedRowKeys.value)
    await batchDeleteGenTable({ ids: selectedRowKeys.value }, reload)
    selectedRowKeys.value = []
  }

  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return []
  }

  const handlerSuccess = () => {
    reload()
  }

  const handleImportTable = async (data) => {
    await importDbTable(data)
    createMessage.success("导入成功")
    await clearSelectedRowKeys()
    reload()
  }

  const handleSyncDbTable = async (record) => {
    const key = "code_gen_info_sync"
    createMessage.loading({
      content: "同步中...",
      key,
    })
    try {
      await syncDbTable({ id: record.id })
      createMessage.success("同步成功")
      reload()
    } finally {
      createMessage.destroy(key)
    }
  }
</script>
